<template>
  <div class="ebook-reader">
    <div id="read"></div>
  </div>
</template>

<script type="text/ecmascript-6">
import { ebookMixin } from 'utils/mixin'
import Epub from 'epubjs'
import {
  getFontFamily,
  saveFontFamily,
  getFontSize,
  saveFontSize,
  getTheme,
  saveTheme,
  getLocation
} from 'utils/localStorage'
import { flatten } from 'utils/book'
global.ePub = Epub
export default {
  mixins: [ebookMixin],
  methods: {
    prevPage() {
      if (this.rendition) {
        this.rendition.prev().then(() => {
          this.refreshLocation()
        })
        this.hideTitleAndMenu()
        if (this.section !== this.currentBook.section().index) {
          this.setSection(this.currentBook.section().index)
        }
      }
    },
    nextPage() {
      if (this.rendition) {
        this.rendition.next().then(() => {
          this.refreshLocation()
        })
        this.hideTitleAndMenu()
        if (this.section !== this.currentBook.section().index) {
          this.setSection(this.currentBook.section().index)
        }
      }
    },
    toggleTitleAndMenu() {
      this.setMenuVisible(!this.menuVisible)
      if (this.menuVisible === false) {
        this.setSettingVisible(-1)
        this.setFontFamilyVisible(false)
      }
    },
    initFontSize() {
      let fontSize = getFontSize(this.fileName)
      if (!fontSize) {
        saveFontSize(this.fileName, this.defaultFontSize)
      } else {
        this.rendition.themes.fontSize(fontSize)
        this.setDefaultFontSize(fontSize)
      }
    },
    initFontFamily() {
      let font = getFontFamily(this.fileName)
      if (!font) {
        saveFontFamily(this.fileName, this.defaultFontFamily)
      } else {
        this.rendition.themes.font(font)
        this.setDefaultFontFamily(font)
      }
    },
    initTheme() {
      let defaultTheme = getTheme(this.fileName)
      if (!defaultTheme) {
        defaultTheme = this.themeList[0].name
        saveTheme(this.fileName, defaultTheme)
      }
      this.setDefaultTheme(defaultTheme)
      this.themeList.forEach((theme) => {
        // 注册主题
        this.rendition.themes.register(theme.name, theme.style)
      })
      // 设置主题
      this.rendition.themes.select(this.defaultTheme)
    },
    initRendition() {
      this.rendition = this.book.renderTo('read', {
        width: window.innerWidth,
        height: window.innerHeight,
        // 微信兼容性配置，这样微信上就能正常显示
        method: 'default'
      })
      const location = getLocation(this.fileName)
      this.display(location, () => {
        this.initTheme()
        this.initFontSize()
        this.initFontFamily()
        this.initGlobalStyle()
        if (this.currentBook.section() && this.currentBook.section().index) {
          // 如果电子书渲染完毕有了章节信息，就存储section的index序号到vuex
          this.setSection(this.currentBook.section().index)
        }
      })
      this.rendition.hooks.content.register((contents) => {
        // 手动添加样式文件
        Promise.all([
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/cabin.css`
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/daysOne.css`
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/montserrat.css`
          ),
          contents.addStylesheet(
            `${process.env.VUE_APP_RES_URL}/fonts/tangerine.css`
          )
        ]).then(() => {
          // console.log('字体全部加载完毕...')
        })
      })
    },
    initGesture() {
      // 监听翻页
      this.rendition.on('touchstart', (event) => {
        this.touchStartX = event.changedTouches[0].clientX
        this.touchStartTime = event.timeStamp
      })
      this.rendition.on('touchend', (event) => {
        const offsetX = event.changedTouches[0].clientX - this.touchStartX
        // 两个操作的时间相减，如果间隔时间过长，则无效（本课程规定不大于500毫秒）
        const time = event.timeStamp - this.touchStartTime
        if (time < 500 && offsetX > 40) {
          this.prevPage()
        } else if (time < 500 && offsetX < -40) {
          this.nextPage()
        } else {
          this.toggleTitleAndMenu()
        }
        // 阻止默认事件和冒泡
        event.preventDefault()
        event.stopPropagation()
      })
    },
    parseBook() {
      this.book.loaded.cover.then(cover => {
        this.book.archive.createUrl(cover).then(url => {
          this.setCover(url)
        })
      })
      this.book.loaded.metadata.then(metadata => {
        this.setMetadata(metadata)
      })
      this.book.loaded.navigation.then(nav => {
        const navItem = flatten(nav.toc)
        function find(item, level = 0) {
         return !item.parent ? level : find(navItem.filter(parentItem => parentItem.id === item.parent)[0], ++level)
        }
        navItem.forEach(item => {
          item.level = find(item)
        })
        this.setNavigation(navItem)
      })
    },
    initEpub() {
      const url = `${process.env.VUE_APP_RES_URL}/epub/${this.fileName}.epub`
      this.book = new Epub(url)
      this.setCurrentBook(this.book)
      this.initRendition()
      this.initGesture()
      this.parseBook()
      this.book.ready
        .then(() => {
          // 不太精确的分页算法，用来获取百分比
          return this.book.locations.generate(
            ((750 * window.innerWidth) / 375) *
              (getFontSize(this.fileName) / 16)
          )
        })
        .then((locations) => {
          // locations是epub算出的分页
          // console.log(locations)
          this.setBookAvailable(true)
          this.refreshLocation()
        })
    }
  },
  mounted() {
    // 测试网址例：http://localhost:8080/#/ebook/Laws|2016_Book_WhoWillBeTheNextPresident
    // http://localhost:8080/#/ebook/LifeSciences|2016_Book_TechnologicalAndInstitutionalI
    const fileName = this.$route.params.fileName.split('|').join('/')
    // 动态路由：this.$route.params.fileName
    this.setFileName(fileName).then(() => {
      this.initEpub()
    })
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
@import '~assets/styles/global';
</style>
